home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / urllib2.py < prev    next >
Encoding:
Python Source  |  2003-07-30  |  37.9 KB  |  1,165 lines

  1. """An extensible library for opening URLs using a variety of protocols
  2.  
  3. The simplest way to use this module is to call the urlopen function,
  4. which accepts a string containing a URL or a Request object (described
  5. below).  It opens the URL and returns the results as file-like
  6. object; the returned object has some extra methods described below.
  7.  
  8. The OpenerDirector manages a collection of Handler objects that do
  9. all the actual work.  Each Handler implements a particular protocol or
  10. option.  The OpenerDirector is a composite object that invokes the
  11. Handlers needed to open the requested URL.  For example, the
  12. HTTPHandler performs HTTP GET and POST requests and deals with
  13. non-error returns.  The HTTPRedirectHandler automatically deals with
  14. HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
  15. deals with digest authentication.
  16.  
  17. urlopen(url, data=None) -- basic usage is that same as original
  18. urllib.  pass the url and optionally data to post to an HTTP URL, and
  19. get a file-like object back.  One difference is that you can also pass
  20. a Request instance instead of URL.  Raises a URLError (subclass of
  21. IOError); for HTTP errors, raises an HTTPError, which can also be
  22. treated as a valid response.
  23.  
  24. build_opener -- function that creates a new OpenerDirector instance.
  25. will install the default handlers.  accepts one or more Handlers as
  26. arguments, either instances or Handler classes that it will
  27. instantiate.  if one of the argument is a subclass of the default
  28. handler, the argument will be installed instead of the default.
  29.  
  30. install_opener -- installs a new opener as the default opener.
  31.  
  32. objects of interest:
  33. OpenerDirector --
  34.  
  35. Request -- an object that encapsulates the state of a request.  the
  36. state can be a simple as the URL.  it can also include extra HTTP
  37. headers, e.g. a User-Agent.
  38.  
  39. BaseHandler --
  40.  
  41. exceptions:
  42. URLError-- a subclass of IOError, individual protocols have their own
  43. specific subclass
  44.  
  45. HTTPError-- also a valid HTTP response, so you can treat an HTTP error
  46. as an exceptional event or valid response
  47.  
  48. internals:
  49. BaseHandler and parent
  50. _call_chain conventions
  51.  
  52. Example usage:
  53.  
  54. import urllib2
  55.  
  56. # set up authentication info
  57. authinfo = urllib2.HTTPBasicAuthHandler()
  58. authinfo.add_password('realm', 'host', 'username', 'password')
  59.  
  60. proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
  61.  
  62. # build a new opener that adds authentication and caching FTP handlers
  63. opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
  64.  
  65. # install it
  66. urllib2.install_opener(opener)
  67.  
  68. f = urllib2.urlopen('http://www.python.org/')
  69.  
  70.  
  71. """
  72.  
  73. # XXX issues:
  74. # If an authentication error handler that tries to perform
  75. # authentication for some reason but fails, how should the error be
  76. # signalled?  The client needs to know the HTTP error code.  But if
  77. # the handler knows that the problem was, e.g., that it didn't know
  78. # that hash algo that requested in the challenge, it would be good to
  79. # pass that information along to the client, too.
  80.  
  81. # XXX to do:
  82. # name!
  83. # documentation (getting there)
  84. # complex proxies
  85. # abstract factory for opener
  86. # ftp errors aren't handled cleanly
  87. # gopher can return a socket.error
  88. # check digest against correct (i.e. non-apache) implementation
  89.  
  90. import socket
  91. import httplib
  92. import inspect
  93. import re
  94. import base64
  95. import urlparse
  96. import md5
  97. import mimetypes
  98. import mimetools
  99. import rfc822
  100. import ftplib
  101. import sys
  102. import time
  103. import os
  104. import gopherlib
  105. import posixpath
  106.  
  107. try:
  108.     from cStringIO import StringIO
  109. except ImportError:
  110.     from StringIO import StringIO
  111.  
  112. try:
  113.     import sha
  114. except ImportError:
  115.     # need 1.5.2 final
  116.     sha = None
  117.  
  118. # not sure how many of these need to be gotten rid of
  119. from urllib import unwrap, unquote, splittype, splithost, \
  120.      addinfourl, splitport, splitgophertype, splitquery, \
  121.      splitattr, ftpwrapper, noheaders
  122.  
  123. # support for proxies via environment variables
  124. from urllib import getproxies
  125.  
  126. # support for FileHandler
  127. from urllib import localhost, url2pathname
  128.  
  129. __version__ = "2.0a1"
  130.  
  131. _opener = None
  132. def urlopen(url, data=None):
  133.     global _opener
  134.     if _opener is None:
  135.         _opener = build_opener()
  136.     return _opener.open(url, data)
  137.  
  138. def install_opener(opener):
  139.     global _opener
  140.     _opener = opener
  141.  
  142. # do these error classes make sense?
  143. # make sure all of the IOError stuff is overridden.  we just want to be
  144. # subtypes.
  145.  
  146. class URLError(IOError):
  147.     # URLError is a sub-type of IOError, but it doesn't share any of
  148.     # the implementation.  need to override __init__ and __str__
  149.     def __init__(self, reason):
  150.         self.reason = reason
  151.  
  152.     def __str__(self):
  153.         return '<urlopen error %s>' % self.reason
  154.  
  155. class HTTPError(URLError, addinfourl):
  156.     """Raised when HTTP error occurs, but also acts like non-error return"""
  157.     __super_init = addinfourl.__init__
  158.  
  159.     def __init__(self, url, code, msg, hdrs, fp):
  160.         self.code = code
  161.         self.msg = msg
  162.         self.hdrs = hdrs
  163.         self.fp = fp
  164.         self.filename = url
  165.         # The addinfourl classes depend on fp being a valid file
  166.         # object.  In some cases, the HTTPError may not have a valid
  167.         # file object.  If this happens, the simplest workaround is to
  168.         # not initialize the base classes.
  169.         if fp is not None:
  170.             self.__super_init(fp, hdrs, url)
  171.  
  172.     def __str__(self):
  173.         return 'HTTP Error %s: %s' % (self.code, self.msg)
  174.  
  175.     def __del__(self):
  176.         # XXX is this safe? what if user catches exception, then
  177.         # extracts fp and discards exception?
  178.         if self.fp:
  179.             self.fp.close()
  180.  
  181. class GopherError(URLError):
  182.     pass
  183.  
  184.  
  185. class Request:
  186.  
  187.     def __init__(self, url, data=None, headers={}):
  188.         # unwrap('<URL:type://host/path>') --> 'type://host/path'
  189.         self.__original = unwrap(url)
  190.         self.type = None
  191.         # self.__r_type is what's left after doing the splittype
  192.         self.host = None
  193.         self.port = None
  194.         self.data = data
  195.         self.headers = {}
  196.         for key, value in headers.items():
  197.             self.add_header(key, value)
  198.  
  199.     def __getattr__(self, attr):
  200.         # XXX this is a fallback mechanism to guard against these
  201.         # methods getting called in a non-standard order.  this may be
  202.         # too complicated and/or unnecessary.
  203.         # XXX should the __r_XXX attributes be public?
  204.         if attr[:12] == '_Request__r_':
  205.             name = attr[12:]
  206.             if hasattr(Request, 'get_' + name):
  207.                 getattr(self, 'get_' + name)()
  208.                 return getattr(self, attr)
  209.         raise AttributeError, attr
  210.  
  211.     def get_method(self):
  212.         if self.has_data():
  213.             return "POST"
  214.         else:
  215.             return "GET"
  216.  
  217.     def add_data(self, data):
  218.         self.data = data
  219.  
  220.     def has_data(self):
  221.         return self.data is not None
  222.  
  223.     def get_data(self):
  224.         return self.data
  225.  
  226.     def get_full_url(self):
  227.         return self.__original
  228.  
  229.     def get_type(self):
  230.         if self.type is None:
  231.             self.type, self.__r_type = splittype(self.__original)
  232.             if self.type is None:
  233.                 raise ValueError, "unknown url type: %s" % self.__original
  234.         return self.type
  235.  
  236.     def get_host(self):
  237.         if self.host is None:
  238.             self.host, self.__r_host = splithost(self.__r_type)
  239.             if self.host:
  240.                 self.host = unquote(self.host)
  241.         return self.host
  242.  
  243.     def get_selector(self):
  244.         return self.__r_host
  245.  
  246.     def set_proxy(self, host, type):
  247.         self.host, self.type = host, type
  248.         self.__r_host = self.__original
  249.  
  250.     def add_header(self, key, val):
  251.         # useful for something like authentication
  252.         self.headers[key.capitalize()] = val
  253.  
  254. class OpenerDirector:
  255.     def __init__(self):
  256.         server_version = "Python-urllib/%s" % __version__
  257.         self.addheaders = [('User-agent', server_version)]
  258.         # manage the individual handlers
  259.         self.handlers = []
  260.         self.handle_open = {}
  261.         self.handle_error = {}
  262.  
  263.     def add_handler(self, handler):
  264.         added = 0
  265.         for meth in dir(handler):
  266.             if meth[-5:] == '_open':
  267.                 protocol = meth[:-5]
  268.                 if protocol in self.handle_open:
  269.                     self.handle_open[protocol].append(handler)
  270.                     self.handle_open[protocol].sort()
  271.                 else:
  272.                     self.handle_open[protocol] = [handler]
  273.                 added = 1
  274.                 continue
  275.             i = meth.find('_')
  276.             j = meth[i+1:].find('_') + i + 1
  277.             if j != -1 and meth[i+1:j] == 'error':
  278.                 proto = meth[:i]
  279.                 kind = meth[j+1:]
  280.                 try:
  281.                     kind = int(kind)
  282.                 except ValueError:
  283.                     pass
  284.                 dict = self.handle_error.get(proto, {})
  285.                 if kind in dict:
  286.                     dict[kind].append(handler)
  287.                     dict[kind].sort()
  288.                 else:
  289.                     dict[kind] = [handler]
  290.                 self.handle_error[proto] = dict
  291.                 added = 1
  292.                 continue
  293.         if added:
  294.             self.handlers.append(handler)
  295.             self.handlers.sort()
  296.             handler.add_parent(self)
  297.  
  298.     def __del__(self):
  299.         self.close()
  300.  
  301.     def close(self):
  302.         for handler in self.handlers:
  303.             handler.close()
  304.         self.handlers = []
  305.  
  306.     def _call_chain(self, chain, kind, meth_name, *args):
  307.         # XXX raise an exception if no one else should try to handle
  308.         # this url.  return None if you can't but someone else could.
  309.         handlers = chain.get(kind, ())
  310.         for handler in handlers:
  311.             func = getattr(handler, meth_name)
  312.  
  313.             result = func(*args)
  314.             if result is not None:
  315.                 return result
  316.  
  317.     def open(self, fullurl, data=None):
  318.         # accept a URL or a Request object
  319.         if isinstance(fullurl, basestring):
  320.             req = Request(fullurl, data)
  321.         else:
  322.             req = fullurl
  323.             if data is not None:
  324.                 req.add_data(data)
  325.  
  326.         result = self._call_chain(self.handle_open, 'default',
  327.                                   'default_open', req)
  328.         if result:
  329.             return result
  330.  
  331.         type_ = req.get_type()
  332.         result = self._call_chain(self.handle_open, type_, type_ + \
  333.                                   '_open', req)
  334.         if result:
  335.             return result
  336.  
  337.         return self._call_chain(self.handle_open, 'unknown',
  338.                                 'unknown_open', req)
  339.  
  340.     def error(self, proto, *args):
  341.         if proto in ['http', 'https']:
  342.             # XXX http[s] protocols are special-cased
  343.             dict = self.handle_error['http'] # https is not different than http
  344.             proto = args[2]  # YUCK!
  345.             meth_name = 'http_error_%d' % proto
  346.             http_err = 1
  347.             orig_args = args
  348.         else:
  349.             dict = self.handle_error
  350.             meth_name = proto + '_error'
  351.             http_err = 0
  352.         args = (dict, proto, meth_name) + args
  353.         result = self._call_chain(*args)
  354.         if result:
  355.             return result
  356.  
  357.         if http_err:
  358.             args = (dict, 'default', 'http_error_default') + orig_args
  359.             return self._call_chain(*args)
  360.  
  361. # XXX probably also want an abstract factory that knows when it makes
  362. # sense to skip a superclass in favor of a subclass and when it might
  363. # make sense to include both
  364.  
  365. def build_opener(*handlers):
  366.     """Create an opener object from a list of handlers.
  367.  
  368.     The opener will use several default handlers, including support
  369.     for HTTP and FTP.
  370.  
  371.     If any of the handlers passed as arguments are subclasses of the
  372.     default handlers, the default handlers will not be used.
  373.     """
  374.  
  375.     opener = OpenerDirector()
  376.     default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
  377.                        HTTPDefaultErrorHandler, HTTPRedirectHandler,
  378.                        FTPHandler, FileHandler]
  379.     if hasattr(httplib, 'HTTPS'):
  380.         default_classes.append(HTTPSHandler)
  381.     skip = []
  382.     for klass in default_classes:
  383.         for check in handlers:
  384.             if inspect.isclass(check):
  385.                 if issubclass(check, klass):
  386.                     skip.append(klass)
  387.             elif isinstance(check, klass):
  388.                 skip.append(klass)
  389.     for klass in skip:
  390.         default_classes.remove(klass)
  391.  
  392.     for klass in default_classes:
  393.         opener.add_handler(klass())
  394.  
  395.     for h in handlers:
  396.         if inspect.isclass(h):
  397.             h = h()
  398.         opener.add_handler(h)
  399.     return opener
  400.  
  401. class BaseHandler:
  402.     handler_order = 500
  403.  
  404.     def add_parent(self, parent):
  405.         self.parent = parent
  406.     def close(self):
  407.         self.parent = None
  408.     def __lt__(self, other):
  409.         if not hasattr(other, "handler_order"):
  410.             # Try to preserve the old behavior of having custom classes
  411.             # inserted after default ones (works only for custom user
  412.             # classes which are not aware of handler_order).
  413.             return True
  414.         return self.handler_order < other.handler_order
  415.  
  416.  
  417. class HTTPDefaultErrorHandler(BaseHandler):
  418.     def http_error_default(self, req, fp, code, msg, hdrs):
  419.         raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
  420.  
  421. class HTTPRedirectHandler(BaseHandler):
  422.     def redirect_request(self, req, fp, code, msg, headers, newurl):
  423.         """Return a Request or None in response to a redirect.
  424.  
  425.         This is called by the http_error_30x methods when a
  426.         redirection response is received.  If a redirection should
  427.         take place, return a new Request to allow http_error_30x to
  428.         perform the redirect.  Otherwise, raise HTTPError if no-one
  429.         else should try to handle this url.  Return None if you can't
  430.         but another Handler might.
  431.         """
  432.         m = req.get_method()
  433.         if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
  434.             or code in (301, 302, 303) and m == "POST"):
  435.             # Strictly (according to RFC 2616), 301 or 302 in response
  436.             # to a POST MUST NOT cause a redirection without confirmation
  437.             # from the user (of urllib2, in this case).  In practice,
  438.             # essentially all clients do redirect in this case, so we
  439.             # do the same.
  440.             return Request(newurl, headers=req.headers)
  441.         else:
  442.             raise HTTPError(req.get_full_url(), code, msg, headers, fp)
  443.  
  444.     # Implementation note: To avoid the server sending us into an
  445.     # infinite loop, the request object needs to track what URLs we
  446.     # have already seen.  Do this by adding a handler-specific
  447.     # attribute to the Request object.
  448.     def http_error_302(self, req, fp, code, msg, headers):
  449.         if 'location' in headers:
  450.             newurl = headers['location']
  451.         elif 'uri' in headers:
  452.             newurl = headers['uri']
  453.         else:
  454.             return
  455.         newurl = urlparse.urljoin(req.get_full_url(), newurl)
  456.  
  457.         # XXX Probably want to forget about the state of the current
  458.         # request, although that might interact poorly with other
  459.         # handlers that also use handler-specific request attributes
  460.         new = self.redirect_request(req, fp, code, msg, headers, newurl)
  461.         if new is None:
  462.             return
  463.  
  464.         # loop detection
  465.         new.error_302_dict = {}
  466.         if hasattr(req, 'error_302_dict'):
  467.             if len(req.error_302_dict)>10 or \
  468.                newurl in req.error_302_dict:
  469.                 raise HTTPError(req.get_full_url(), code,
  470.                                 self.inf_msg + msg, headers, fp)
  471.             new.error_302_dict.update(req.error_302_dict)
  472.         new.error_302_dict[newurl] = newurl
  473.  
  474.         # Don't close the fp until we are sure that we won't use it
  475.         # with HTTPError.
  476.         fp.read()
  477.         fp.close()
  478.  
  479.         return self.parent.open(new)
  480.  
  481.     http_error_301 = http_error_303 = http_error_307 = http_error_302
  482.  
  483.     inf_msg = "The HTTP server returned a redirect error that would " \
  484.               "lead to an infinite loop.\n" \
  485.               "The last 30x error message was:\n"
  486.  
  487. class ProxyHandler(BaseHandler):
  488.     # Proxies must be in front
  489.     handler_order = 100
  490.  
  491.     def __init__(self, proxies=None):
  492.         if proxies is None:
  493.             proxies = getproxies()
  494.         assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  495.         self.proxies = proxies
  496.         for type, url in proxies.items():
  497.             setattr(self, '%s_open' % type,
  498.                     lambda r, proxy=url, type=type, meth=self.proxy_open: \
  499.                     meth(r, proxy, type))
  500.  
  501.     def proxy_open(self, req, proxy, type):
  502.         orig_type = req.get_type()
  503.         type, r_type = splittype(proxy)
  504.         host, XXX = splithost(r_type)
  505.         if '@' in host:
  506.             user_pass, host = host.split('@', 1)
  507.             if ':' in user_pass:
  508.                 user, password = user_pass.split(':', 1)
  509.                 user_pass = base64.encodestring('%s:%s' % (unquote(user),
  510.                                                            unquote(password)))
  511.                 req.add_header('Proxy-authorization', 'Basic ' + user_pass)
  512.         host = unquote(host)
  513.         req.set_proxy(host, type)
  514.         if orig_type == type:
  515.             # let other handlers take care of it
  516.             # XXX this only makes sense if the proxy is before the
  517.             # other handlers
  518.             return None
  519.         else:
  520.             # need to start over, because the other handlers don't
  521.             # grok the proxy's URL type
  522.             return self.parent.open(req)
  523.  
  524. # feature suggested by Duncan Booth
  525. # XXX custom is not a good name
  526. class CustomProxy:
  527.     # either pass a function to the constructor or override handle
  528.     def __init__(self, proto, func=None, proxy_addr=None):
  529.         self.proto = proto
  530.         self.func = func
  531.         self.addr = proxy_addr
  532.  
  533.     def handle(self, req):
  534.         if self.func and self.func(req):
  535.             return 1
  536.  
  537.     def get_proxy(self):
  538.         return self.addr
  539.  
  540. class CustomProxyHandler(BaseHandler):
  541.     # Proxies must be in front
  542.     handler_order = 100
  543.  
  544.     def __init__(self, *proxies):
  545.         self.proxies = {}
  546.  
  547.     def proxy_open(self, req):
  548.         proto = req.get_type()
  549.         try:
  550.             proxies = self.proxies[proto]
  551.         except KeyError:
  552.             return None
  553.         for p in proxies:
  554.             if p.handle(req):
  555.                 req.set_proxy(p.get_proxy())
  556.                 return self.parent.open(req)
  557.         return None
  558.  
  559.     def do_proxy(self, p, req):
  560.         return self.parent.open(req)
  561.  
  562.     def add_proxy(self, cpo):
  563.         if cpo.proto in self.proxies:
  564.             self.proxies[cpo.proto].append(cpo)
  565.         else:
  566.             self.proxies[cpo.proto] = [cpo]
  567.  
  568. class HTTPPasswordMgr:
  569.     def __init__(self):
  570.         self.passwd = {}
  571.  
  572.     def add_password(self, realm, uri, user, passwd):
  573.         # uri could be a single URI or a sequence
  574.         if isinstance(uri, basestring):
  575.             uri = [uri]
  576.         uri = tuple(map(self.reduce_uri, uri))
  577.         if not realm in self.passwd:
  578.             self.passwd[realm] = {}
  579.         self.passwd[realm][uri] = (user, passwd)
  580.  
  581.     def find_user_password(self, realm, authuri):
  582.         domains = self.passwd.get(realm, {})
  583.         authuri = self.reduce_uri(authuri)
  584.         for uris, authinfo in domains.iteritems():
  585.             for uri in uris:
  586.                 if self.is_suburi(uri, authuri):
  587.                     return authinfo
  588.         return None, None
  589.  
  590.     def reduce_uri(self, uri):
  591.         """Accept netloc or URI and extract only the netloc and path"""
  592.         parts = urlparse.urlparse(uri)
  593.         if parts[1]:
  594.             return parts[1], parts[2] or '/'
  595.         else:
  596.             return parts[2], '/'
  597.  
  598.     def is_suburi(self, base, test):
  599.         """Check if test is below base in a URI tree
  600.  
  601.         Both args must be URIs in reduced form.
  602.         """
  603.         if base == test:
  604.             return True
  605.         if base[0] != test[0]:
  606.             return False
  607.         common = posixpath.commonprefix((base[1], test[1]))
  608.         if len(common) == len(base[1]):
  609.             return True
  610.         return False
  611.  
  612.  
  613. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  614.  
  615.     def find_user_password(self, realm, authuri):
  616.         user, password = HTTPPasswordMgr.find_user_password(self, realm,
  617.                                                             authuri)
  618.         if user is not None:
  619.             return user, password
  620.         return HTTPPasswordMgr.find_user_password(self, None, authuri)
  621.  
  622.  
  623. class AbstractBasicAuthHandler:
  624.  
  625.     rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
  626.  
  627.     # XXX there can actually be multiple auth-schemes in a
  628.     # www-authenticate header.  should probably be a lot more careful
  629.     # in parsing them to extract multiple alternatives
  630.  
  631.     def __init__(self, password_mgr=None):
  632.         if password_mgr is None:
  633.             password_mgr = HTTPPasswordMgr()
  634.         self.passwd = password_mgr
  635.         self.add_password = self.passwd.add_password
  636.  
  637.     def http_error_auth_reqed(self, authreq, host, req, headers):
  638.         # XXX could be multiple headers
  639.         authreq = headers.get(authreq, None)
  640.         if authreq:
  641.             mo = AbstractBasicAuthHandler.rx.match(authreq)
  642.             if mo:
  643.                 scheme, realm = mo.groups()
  644.                 if scheme.lower() == 'basic':
  645.                     return self.retry_http_basic_auth(host, req, realm)
  646.  
  647.     def retry_http_basic_auth(self, host, req, realm):
  648.         user,pw = self.passwd.find_user_password(realm, host)
  649.         if pw:
  650.             raw = "%s:%s" % (user, pw)
  651.             auth = 'Basic %s' % base64.encodestring(raw).strip()
  652.             if req.headers.get(self.auth_header, None) == auth:
  653.                 return None
  654.             req.add_header(self.auth_header, auth)
  655.             return self.parent.open(req)
  656.         else:
  657.             return None
  658.  
  659. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  660.  
  661.     auth_header = 'Authorization'
  662.  
  663.     def http_error_401(self, req, fp, code, msg, headers):
  664.         host = urlparse.urlparse(req.get_full_url())[1]
  665.         return self.http_error_auth_reqed('www-authenticate',
  666.                                           host, req, headers)
  667.  
  668.  
  669. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  670.  
  671.     auth_header = 'Proxy-authorization'
  672.  
  673.     def http_error_407(self, req, fp, code, msg, headers):
  674.         host = req.get_host()
  675.         return self.http_error_auth_reqed('proxy-authenticate',
  676.                                           host, req, headers)
  677.  
  678.  
  679. class AbstractDigestAuthHandler:
  680.  
  681.     def __init__(self, passwd=None):
  682.         if passwd is None:
  683.             passwd = HTTPPasswordMgr()
  684.         self.passwd = passwd
  685.         self.add_password = self.passwd.add_password
  686.  
  687.     def http_error_auth_reqed(self, authreq, host, req, headers):
  688.         authreq = headers.get(self.auth_header, None)
  689.         if authreq:
  690.             kind = authreq.split()[0]
  691.             if kind == 'Digest':
  692.                 return self.retry_http_digest_auth(req, authreq)
  693.  
  694.     def retry_http_digest_auth(self, req, auth):
  695.         token, challenge = auth.split(' ', 1)
  696.         chal = parse_keqv_list(parse_http_list(challenge))
  697.         auth = self.get_authorization(req, chal)
  698.         if auth:
  699.             auth_val = 'Digest %s' % auth
  700.             if req.headers.get(self.auth_header, None) == auth_val:
  701.                 return None
  702.             req.add_header(self.auth_header, auth_val)
  703.             resp = self.parent.open(req)
  704.             return resp
  705.  
  706.     def get_authorization(self, req, chal):
  707.         try:
  708.             realm = chal['realm']
  709.             nonce = chal['nonce']
  710.             algorithm = chal.get('algorithm', 'MD5')
  711.             # mod_digest doesn't send an opaque, even though it isn't
  712.             # supposed to be optional
  713.             opaque = chal.get('opaque', None)
  714.         except KeyError:
  715.             return None
  716.  
  717.         H, KD = self.get_algorithm_impls(algorithm)
  718.         if H is None:
  719.             return None
  720.  
  721.         user, pw = self.passwd.find_user_password(realm,
  722.                                                   req.get_full_url())
  723.         if user is None:
  724.             return None
  725.  
  726.         # XXX not implemented yet
  727.         if req.has_data():
  728.             entdig = self.get_entity_digest(req.get_data(), chal)
  729.         else:
  730.             entdig = None
  731.  
  732.         A1 = "%s:%s:%s" % (user, realm, pw)
  733.         A2 = "%s:%s" % (req.has_data() and 'POST' or 'GET',
  734.                         # XXX selector: what about proxies and full urls
  735.                         req.get_selector())
  736.         respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
  737.         # XXX should the partial digests be encoded too?
  738.  
  739.         base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  740.                'response="%s"' % (user, realm, nonce, req.get_selector(),
  741.                                   respdig)
  742.         if opaque:
  743.             base = base + ', opaque="%s"' % opaque
  744.         if entdig:
  745.             base = base + ', digest="%s"' % entdig
  746.         if algorithm != 'MD5':
  747.             base = base + ', algorithm="%s"' % algorithm
  748.         return base
  749.  
  750.     def get_algorithm_impls(self, algorithm):
  751.         # lambdas assume digest modules are imported at the top level
  752.         if algorithm == 'MD5':
  753.             H = lambda x, e=encode_digest:e(md5.new(x).digest())
  754.         elif algorithm == 'SHA':
  755.             H = lambda x, e=encode_digest:e(sha.new(x).digest())
  756.         # XXX MD5-sess
  757.         KD = lambda s, d, H=H: H("%s:%s" % (s, d))
  758.         return H, KD
  759.  
  760.     def get_entity_digest(self, data, chal):
  761.         # XXX not implemented yet
  762.         return None
  763.  
  764.  
  765. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  766.     """An authentication protocol defined by RFC 2069
  767.  
  768.     Digest authentication improves on basic authentication because it
  769.     does not transmit passwords in the clear.
  770.     """
  771.  
  772.     auth_header = 'Authorization'
  773.  
  774.     def http_error_401(self, req, fp, code, msg, headers):
  775.         host = urlparse.urlparse(req.get_full_url())[1]
  776.         self.http_error_auth_reqed('www-authenticate', host, req, headers)
  777.  
  778.  
  779. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  780.  
  781.     auth_header = 'Proxy-Authorization'
  782.  
  783.     def http_error_407(self, req, fp, code, msg, headers):
  784.         host = req.get_host()
  785.         self.http_error_auth_reqed('proxy-authenticate', host, req, headers)
  786.  
  787.  
  788. def encode_digest(digest):
  789.     hexrep = []
  790.     for c in digest:
  791.         n = (ord(c) >> 4) & 0xf
  792.         hexrep.append(hex(n)[-1])
  793.         n = ord(c) & 0xf
  794.         hexrep.append(hex(n)[-1])
  795.     return ''.join(hexrep)
  796.  
  797.  
  798. class AbstractHTTPHandler(BaseHandler):
  799.  
  800.     # XXX Should rewrite do_open() to use the new httplib interface,
  801.     # would would be a little simpler.
  802.  
  803.     def do_open(self, http_class, req):
  804.         host = req.get_host()
  805.         if not host:
  806.             raise URLError('no host given')
  807.  
  808.         h = http_class(host) # will parse host:port
  809.         if req.has_data():
  810.             data = req.get_data()
  811.             h.putrequest('POST', req.get_selector())
  812.             if not 'Content-type' in req.headers:
  813.                 h.putheader('Content-type',
  814.                             'application/x-www-form-urlencoded')
  815.             if not 'Content-length' in req.headers:
  816.                 h.putheader('Content-length', '%d' % len(data))
  817.         else:
  818.             h.putrequest('GET', req.get_selector())
  819.  
  820.         scheme, sel = splittype(req.get_selector())
  821.         sel_host, sel_path = splithost(sel)
  822.         h.putheader('Host', sel_host or host)
  823.         for name, value in self.parent.addheaders:
  824.             name = name.capitalize()
  825.             if name not in req.headers:
  826.                 h.putheader(name, value)
  827.         for k, v in req.headers.items():
  828.             h.putheader(k, v)
  829.         # httplib will attempt to connect() here.  be prepared
  830.         # to convert a socket error to a URLError.
  831.         try:
  832.             h.endheaders()
  833.         except socket.error, err:
  834.             raise URLError(err)
  835.         if req.has_data():
  836.             h.send(data)
  837.  
  838.         code, msg, hdrs = h.getreply()
  839.         fp = h.getfile()
  840.         if code == 200:
  841.             return addinfourl(fp, hdrs, req.get_full_url())
  842.         else:
  843.             return self.parent.error('http', req, fp, code, msg, hdrs)
  844.  
  845.  
  846. class HTTPHandler(AbstractHTTPHandler):
  847.  
  848.     def http_open(self, req):
  849.         return self.do_open(httplib.HTTP, req)
  850.  
  851.  
  852. if hasattr(httplib, 'HTTPS'):
  853.     class HTTPSHandler(AbstractHTTPHandler):
  854.  
  855.         def https_open(self, req):
  856.             return self.do_open(httplib.HTTPS, req)
  857.  
  858.  
  859. class UnknownHandler(BaseHandler):
  860.     def unknown_open(self, req):
  861.         type = req.get_type()
  862.         raise URLError('unknown url type: %s' % type)
  863.  
  864. def parse_keqv_list(l):
  865.     """Parse list of key=value strings where keys are not duplicated."""
  866.     parsed = {}
  867.     for elt in l:
  868.         k, v = elt.split('=', 1)
  869.         if v[0] == '"' and v[-1] == '"':
  870.             v = v[1:-1]
  871.         parsed[k] = v
  872.     return parsed
  873.  
  874. def parse_http_list(s):
  875.     """Parse lists as described by RFC 2068 Section 2.
  876.  
  877.     In particular, parse comman-separated lists where the elements of
  878.     the list may include quoted-strings.  A quoted-string could
  879.     contain a comma.
  880.     """
  881.     # XXX this function could probably use more testing
  882.  
  883.     list = []
  884.     end = len(s)
  885.     i = 0
  886.     inquote = 0
  887.     start = 0
  888.     while i < end:
  889.         cur = s[i:]
  890.         c = cur.find(',')
  891.         q = cur.find('"')
  892.         if c == -1:
  893.             list.append(s[start:])
  894.             break
  895.         if q == -1:
  896.             if inquote:
  897.                 raise ValueError, "unbalanced quotes"
  898.             else:
  899.                 list.append(s[start:i+c])
  900.                 i = i + c + 1
  901.                 continue
  902.         if inquote:
  903.             if q < c:
  904.                 list.append(s[start:i+c])
  905.                 i = i + c + 1
  906.                 start = i
  907.                 inquote = 0
  908.             else:
  909.                 i = i + q
  910.         else:
  911.             if c < q:
  912.                 list.append(s[start:i+c])
  913.                 i = i + c + 1
  914.                 start = i
  915.             else:
  916.                 inquote = 1
  917.                 i = i + q + 1
  918.     return map(lambda x: x.strip(), list)
  919.  
  920. class FileHandler(BaseHandler):
  921.     # Use local file or FTP depending on form of URL
  922.     def file_open(self, req):
  923.         url = req.get_selector()
  924.         if url[:2] == '//' and url[2:3] != '/':
  925.             req.type = 'ftp'
  926.             return self.parent.open(req)
  927.         else:
  928.             return self.open_local_file(req)
  929.  
  930.     # names for the localhost
  931.     names = None
  932.     def get_names(self):
  933.         if FileHandler.names is None:
  934.             FileHandler.names = (socket.gethostbyname('localhost'),
  935.                                  socket.gethostbyname(socket.gethostname()))
  936.         return FileHandler.names
  937.  
  938.     # not entirely sure what the rules are here
  939.     def open_local_file(self, req):
  940.         host = req.get_host()
  941.         file = req.get_selector()
  942.         localfile = url2pathname(file)
  943.         stats = os.stat(localfile)
  944.         size = stats.st_size
  945.         modified = rfc822.formatdate(stats.st_mtime)
  946.         mtype = mimetypes.guess_type(file)[0]
  947.         headers = mimetools.Message(StringIO(
  948.             'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
  949.             (mtype or 'text/plain', size, modified)))
  950.         if host:
  951.             host, port = splitport(host)
  952.         if not host or \
  953.            (not port and socket.gethostbyname(host) in self.get_names()):
  954.             return addinfourl(open(localfile, 'rb'),
  955.                               headers, 'file:'+file)
  956.         raise URLError('file not on local host')
  957.  
  958. class FTPHandler(BaseHandler):
  959.     def ftp_open(self, req):
  960.         host = req.get_host()
  961.         if not host:
  962.             raise IOError, ('ftp error', 'no host given')
  963.         # XXX handle custom username & password
  964.         try:
  965.             host = socket.gethostbyname(host)
  966.         except socket.error, msg:
  967.             raise URLError(msg)
  968.         host, port = splitport(host)
  969.         if port is None:
  970.             port = ftplib.FTP_PORT
  971.         path, attrs = splitattr(req.get_selector())
  972.         path = unquote(path)
  973.         dirs = path.split('/')
  974.         dirs, file = dirs[:-1], dirs[-1]
  975.         if dirs and not dirs[0]:
  976.             dirs = dirs[1:]
  977.         user = passwd = '' # XXX
  978.         try:
  979.             fw = self.connect_ftp(user, passwd, host, port, dirs)
  980.             type = file and 'I' or 'D'
  981.             for attr in attrs:
  982.                 attr, value = splitattr(attr)
  983.                 if attr.lower() == 'type' and \
  984.                    value in ('a', 'A', 'i', 'I', 'd', 'D'):
  985.                     type = value.upper()
  986.             fp, retrlen = fw.retrfile(file, type)
  987.             headers = ""
  988.             mtype = mimetypes.guess_type(req.get_full_url())[0]
  989.             if mtype:
  990.                 headers += "Content-type: %s\n" % mtype
  991.             if retrlen is not None and retrlen >= 0:
  992.                 headers += "Content-length: %d\n" % retrlen
  993.             sf = StringIO(headers)
  994.             headers = mimetools.Message(sf)
  995.             return addinfourl(fp, headers, req.get_full_url())
  996.         except ftplib.all_errors, msg:
  997.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  998.  
  999.     def connect_ftp(self, user, passwd, host, port, dirs):
  1000.         fw = ftpwrapper(user, passwd, host, port, dirs)
  1001. ##        fw.ftp.set_debuglevel(1)
  1002.         return fw
  1003.  
  1004. class CacheFTPHandler(FTPHandler):
  1005.     # XXX would be nice to have pluggable cache strategies
  1006.     # XXX this stuff is definitely not thread safe
  1007.     def __init__(self):
  1008.         self.cache = {}
  1009.         self.timeout = {}
  1010.         self.soonest = 0
  1011.         self.delay = 60
  1012.         self.max_conns = 16
  1013.  
  1014.     def setTimeout(self, t):
  1015.         self.delay = t
  1016.  
  1017.     def setMaxConns(self, m):
  1018.         self.max_conns = m
  1019.  
  1020.     def connect_ftp(self, user, passwd, host, port, dirs):
  1021.         key = user, passwd, host, port
  1022.         if key in self.cache:
  1023.             self.timeout[key] = time.time() + self.delay
  1024.         else:
  1025.             self.cache[key] = ftpwrapper(user, passwd, host, port, dirs)
  1026.             self.timeout[key] = time.time() + self.delay
  1027.         self.check_cache()
  1028.         return self.cache[key]
  1029.  
  1030.     def check_cache(self):
  1031.         # first check for old ones
  1032.         t = time.time()
  1033.         if self.soonest <= t:
  1034.             for k, v in self.timeout.items():
  1035.                 if v < t:
  1036.                     self.cache[k].close()
  1037.                     del self.cache[k]
  1038.                     del self.timeout[k]
  1039.         self.soonest = min(self.timeout.values())
  1040.  
  1041.         # then check the size
  1042.         if len(self.cache) == self.max_conns:
  1043.             for k, v in self.timeout.items():
  1044.                 if v == self.soonest:
  1045.                     del self.cache[k]
  1046.                     del self.timeout[k]
  1047.                     break
  1048.             self.soonest = min(self.timeout.values())
  1049.  
  1050. class GopherHandler(BaseHandler):
  1051.     def gopher_open(self, req):
  1052.         host = req.get_host()
  1053.         if not host:
  1054.             raise GopherError('no host given')
  1055.         host = unquote(host)
  1056.         selector = req.get_selector()
  1057.         type, selector = splitgophertype(selector)
  1058.         selector, query = splitquery(selector)
  1059.         selector = unquote(selector)
  1060.         if query:
  1061.             query = unquote(query)
  1062.             fp = gopherlib.send_query(selector, query, host)
  1063.         else:
  1064.             fp = gopherlib.send_selector(selector, host)
  1065.         return addinfourl(fp, noheaders(), req.get_full_url())
  1066.  
  1067. #bleck! don't use this yet
  1068. class OpenerFactory:
  1069.  
  1070.     default_handlers = [UnknownHandler, HTTPHandler,
  1071.                         HTTPDefaultErrorHandler, HTTPRedirectHandler,
  1072.                         FTPHandler, FileHandler]
  1073.     handlers = []
  1074.     replacement_handlers = []
  1075.  
  1076.     def add_handler(self, h):
  1077.         self.handlers = self.handlers + [h]
  1078.  
  1079.     def replace_handler(self, h):
  1080.         pass
  1081.  
  1082.     def build_opener(self):
  1083.         opener = OpenerDirector()
  1084.         for ph in self.default_handlers:
  1085.             if inspect.isclass(ph):
  1086.                 ph = ph()
  1087.             opener.add_handler(ph)
  1088.  
  1089. if __name__ == "__main__":
  1090.     # XXX some of the test code depends on machine configurations that
  1091.     # are internal to CNRI.   Need to set up a public server with the
  1092.     # right authentication configuration for test purposes.
  1093.     if socket.gethostname() == 'bitdiddle':
  1094.         localhost = 'bitdiddle.cnri.reston.va.us'
  1095.     elif socket.gethostname() == 'bitdiddle.concentric.net':
  1096.         localhost = 'localhost'
  1097.     else:
  1098.         localhost = None
  1099.     urls = [
  1100.         # Thanks to Fred for finding these!
  1101.         'gopher://gopher.lib.ncsu.edu/11/library/stacks/Alex',
  1102.         'gopher://gopher.vt.edu:10010/10/33',
  1103.  
  1104.         'file:/etc/passwd',
  1105.         'file://nonsensename/etc/passwd',
  1106.         'ftp://www.python.org/pub/python/misc/sousa.au',
  1107.         'ftp://www.python.org/pub/tmp/blat',
  1108.         'http://www.espn.com/', # redirect
  1109.         'http://www.python.org/Spanish/Inquistion/',
  1110.         ('http://www.python.org/cgi-bin/faqw.py',
  1111.          'query=pythonistas&querytype=simple&casefold=yes&req=search'),
  1112.         'http://www.python.org/',
  1113.         'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC/research-reports/00README-Legal-Rules-Regs',
  1114.             ]
  1115.  
  1116. ##    if localhost is not None:
  1117. ##        urls = urls + [
  1118. ##            'file://%s/etc/passwd' % localhost,
  1119. ##            'http://%s/simple/' % localhost,
  1120. ##            'http://%s/digest/' % localhost,
  1121. ##            'http://%s/not/found.h' % localhost,
  1122. ##            ]
  1123.  
  1124. ##        bauth = HTTPBasicAuthHandler()
  1125. ##        bauth.add_password('basic_test_realm', localhost, 'jhylton',
  1126. ##                           'password')
  1127. ##        dauth = HTTPDigestAuthHandler()
  1128. ##        dauth.add_password('digest_test_realm', localhost, 'jhylton',
  1129. ##                           'password')
  1130.  
  1131.  
  1132.     cfh = CacheFTPHandler()
  1133.     cfh.setTimeout(1)
  1134.  
  1135. ##    # XXX try out some custom proxy objects too!
  1136. ##    def at_cnri(req):
  1137. ##        host = req.get_host()
  1138. ##        print host
  1139. ##        if host[-18:] == '.cnri.reston.va.us':
  1140. ##            return 1
  1141. ##    p = CustomProxy('http', at_cnri, 'proxy.cnri.reston.va.us')
  1142. ##    ph = CustomProxyHandler(p)
  1143.  
  1144. ##    install_opener(build_opener(dauth, bauth, cfh, GopherHandler, ph))
  1145.     install_opener(build_opener(cfh, GopherHandler))
  1146.  
  1147.     for url in urls:
  1148.         if isinstance(url, tuple):
  1149.             url, req = url
  1150.         else:
  1151.             req = None
  1152.         print url
  1153.         try:
  1154.             f = urlopen(url, req)
  1155.         except IOError, err:
  1156.             print "IOError:", err
  1157.         except socket.error, err:
  1158.             print "socket.error:", err
  1159.         else:
  1160.             buf = f.read()
  1161.             f.close()
  1162.             print "read %d bytes" % len(buf)
  1163.         print
  1164.         time.sleep(0.1)
  1165.